-- UIPhoneNumberRecord
-- Created by huanghr Oct/11/2016
-- 手机号记录和身份证记录

local REQUEST_INTERVAL = 60;

UIPhoneNumberRecord = class("UIPhoneNumberRecord", function()
    return cc.Layer:create();
end);

function UIPhoneNumberRecord.create()
    return UIPhoneNumberRecord.new();
end

-- 构造函数
function UIPhoneNumberRecord:ctor()
    self:setName("UIPhoneNumberRecord");
    local node = cc.CSLoader:createNode("layout/setting/PhoneNumber.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    -- 打开页面的时候需要检测上次生成验证码时间
    self:checkIsTimeout();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 检测时间是否超时
function UIPhoneNumberRecord:checkIsTimeout()
    if PhoneNumberRecordM.checkTimeout() then
        -- 已经超时，删除请求信息
        PhoneNumberRecordM.deleteRequestInfo();
    end
end

-- 适配
function UIPhoneNumberRecord:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIPhoneNumberRecord:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIPhoneNumberRecord 界面析构清理");
            EventMgr.removeAll("UIPhoneNumberRecord");

            -- 显示系统设置界面
            local uiForm = UIMgr:getCurrentScene():getFormByName("UISystemSetting");
            if uiForm then
                uiForm:setVisible(true);
                playAppearEffect(uiForm);
            end
        elseif ev == "enter" then
            -- 隐藏掉系统设置界面
            local uiForm = UIMgr:getCurrentScene():getFormByName("UISystemSetting");
            if uiForm then
                uiForm:setVisible(false);
            end
        end
    end);
end

-- 注册点击事件
function UIPhoneNumberRecord:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIPhoneNumberRecord");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 发送验证码
    local CT = findChildByName(self.node, "CT");

    local btnAuthCode = findChildByName(CT, "auth_code/operate_btn");
    local function onSendCode(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            self.phoneStr = string.trim(self.editPhoneNum:getText());

            -- 先检查手机号码是否符合
            if not PhoneNumberRecordM.checkPhoneNumIsOk(self.phoneStr) then
                 alert(getLocStr("phone_number_is_wrong"));

                 return;
            end

            -- 记录下请求信息
            PhoneNumberRecordM.setRequestInfo(self.phoneStr);

            -- 合法生成验证码
            Operation.cmd_generate_phone_auth_code(self.phoneStr);

            -- 检查时间更新
            self:checkResendTime();

            -- 检查更新
            local btnBind = findChildByName(CT, "bind_node/operate_btn");
            btnBind:setTouchEnabled(true);
            btnBind:setBright(true);
        end
    end
    btnAuthCode:addTouchEventListener(onSendCode);

    -- 记录手机号
    local btnBind = findChildByName(CT, "bind_node/operate_btn");

    -- 检查验证码
    local function bindPhoneNumber(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local authStr = string.trim(self.editAuthNum:getText());

            if PhoneNumberRecordM.checkAuthCode(authStr) then

                local phoneStr = PhoneNumberRecordM.queryRequestInfo("phone_number");

                -- 请求记录手机号
                Operation.cmd_record_phone_number(phoneStr, PhoneNumberRecordM.OPERATE_RECORD_PHONE_NUMBER, authStr);
            else
                alert(getLocStr("your_auth_code_error"));
            end
        end
    end

    btnBind:addTouchEventListener(bindPhoneNumber);
end


-- 重绘
function UIPhoneNumberRecord:redraw()
    -- 标题
    local CT = findChildByName(self.node, "CT");
    local titleLabel = findChildByName(CT, "bg/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("system_phone_record"));

    -- 副标题
    local subTitleLabel = findChildByName(CT, "bg/subhead");
    TextStyleM.setSubheadStyle(subTitleLabel);
    subTitleLabel:setString(getLocStr("first_bind_phone_bonus"));

    -- 步骤1:
    local authNode = findChildByName(CT, "auth_code");
    local inputLabel1 = findChildByName(authNode, "input_tip");
    -- TextStyleM.setTitleStyle(inputLabel1, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
    -- inputLabel1:setString(getLocStr("first_step_bind"));

    local phoneNumberInput = findChildByName(authNode, "input_edit_box");
    -- 手机号码
    local editPhoneNum = ccui.EditBox:create(cc.size(300, 30), "images/ui/login/1.png");
    editPhoneNum:setAnchorPoint(cc.p(0, 0.5));
    editPhoneNum:setPosition(phoneNumberInput:getPosition());
    editPhoneNum:setFontName(getLocFontName());
    editPhoneNum:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);

    editPhoneNum:setPlaceHolder(getLocStr("first_step_bind"));
    editPhoneNum:setPlaceholderFontColor(TextStyleM.TEXT_COLOR_BEIGE);

    editPhoneNum:setPlaceholderFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editPhoneNum:setFontColor(TextStyleM.TEXT_COLOR_DARK_BROWN);
    editPhoneNum:setMaxLength(11);
    editPhoneNum:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC);

    self.editPhoneNum = editPhoneNum;

    -- 如果上次有输入的话就显示已输入
    local lastSubmitPhone = PhoneNumberRecordM.queryRequestInfo("phone_number");
    if type(lastSubmitPhone) == "string" then
        self.editPhoneNum:setText(lastSubmitPhone);
    end

    phoneNumberInput:getParent():addChild(editPhoneNum);
    phoneNumberInput:setVisible(false);



    -- 发送验证码
    local btnOperate1 = findChildByName(authNode, "operate_btn");
    TextStyleM.setTextStyle(btnOperate1, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOperate1:setTitleText(getLocStr("btn_text_send_authcode"));

    -- 步骤2：
    local bindNode = findChildByName(CT, "bind_node");
    local inputLabel2 = findChildByName(bindNode, "input_tip");
    -- TextStyleM.setTitleStyle(inputLabel2, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
    -- inputLabel2:setString(getLocStr("second_step_bind"));

    local authCode = findChildByName(bindNode, "input_edit_box");
    -- 验证码输入
    local editAuthNum = ccui.EditBox:create(cc.size(300, 50), "images/ui/login/1.png");
    editAuthNum:setAnchorPoint(cc.p(0, 0.5));
    editAuthNum:setPosition(authCode:getPosition());
    editAuthNum:setFontName(getLocFontName());
    editAuthNum:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editAuthNum:setPlaceHolder(getLocStr("second_step_bind"));
    editAuthNum:setPlaceholderFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editAuthNum:setPlaceholderFontColor(TextStyleM.TEXT_COLOR_BEIGE);
    editAuthNum:setFontColor(TextStyleM.TEXT_COLOR_DARK_BROWN);
    editAuthNum:setMaxLength(6);
    editAuthNum:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC);
    self.editAuthNum = editAuthNum;
    authCode:getParent():addChild(editAuthNum);
    authCode:setVisible(false);

    -- 记录手机号
    local btnOperate2 = findChildByName(bindNode, "operate_btn");
    TextStyleM.setTextStyle(btnOperate2, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOperate2:setTitleText(getLocStr("btn_text_submit_confirm"));

    -- 根据记录手机号判断，验证码过期后手机号会删除
    if not PhoneNumberRecordM.queryRequestInfo("phone_number") then
        btnOperate2:setTouchEnabled(false);
        btnOperate2:setBright(false);
    end

    self:checkResendTime();
end

-- 检查重新发送的时间
function UIPhoneNumberRecord:checkResendTime()
    -- 检查当前时间是否大于60s
    local requestAuthCodeTime = PhoneNumberRecordM.queryRequestInfo("request_authcode_time");

    -- 发送验证码
    local btnOperate1 = findChildByName(self.node, "CT/auth_code/operate_btn");
    TextStyleM.setTextStyle(btnOperate1, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOperate1:setTitleText(getLocStr("btn_text_send_authcode"));

    -- 默认置灰
    btnOperate1:setTouchEnabled(false);
    btnOperate1:setBright(false);

    -- 没有记录不管
    if requestAuthCodeTime == nil then
        btnOperate1:setTouchEnabled(true);
        btnOperate1:setBright(true);

        return;
    end

    -- 当前时间超过60s可用
    if TimeM.getCurrentTime() - requestAuthCodeTime >= REQUEST_INTERVAL then
        btnOperate1:setTouchEnabled(true);
        btnOperate1:setBright(true);

        return;
    end

    -- 显示倒计时
    local function tick()
        local leftTime = REQUEST_INTERVAL - math.floor(TimeM.getCurrentTime() - requestAuthCodeTime);

        if leftTime <= 0 then
            btnOperate1:setTouchEnabled(true);
            btnOperate1:setBright(true);

            btnOperate1:setTitleText(getLocStr("btn_text_send_authcode"));
            return;
        end

        -- 重新发送的剩余时间
        local leftStr = string.format(getLocStr("after_a_time_resend"), leftTime);

        btnOperate1:setTitleText(leftStr)

        performWithDelay(self.node, tick, 1);
    end

    tick();
end